<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="/static/css/mini-nord.min.css">
  <title>萌点流浪动物救助</title>
</head>
<body>
  <div class="container">
    <div style="margin:100px auto; width:60%; height:400px; background-color: rgba(3,119,165,100); border-radius: 20px;">
      <div style="width:50%; float:left;">
        <h2 style="margin-top:150px; margin-left:50px;">萌点 流浪动物救助</h2>
        <h5 style="margin-left:50px;">找到萌萌们的地点，就是温暖的起点</h5>
      </div>
      <div style="width:50%; height: 400px; float: left; background-color: white;
       border-top-right-radius:20px; border-bottom-right-radius:20px;">
        <form onsubmit="login(this);return false;" autocomplete="off" 
        style="width:50%; height: 200px; background-color: white; border: none; margin-top: 90px; margin-left: 50px;">
          <p style="font-weight: 700;">登录</p>
          <input style="width: 250px;border:0;border-bottom:1px solid #ccc;outline: none;background-color: #fff;" type="text" name="username" oninput="cacheInput(this);" placeholder="用户名" required>
          <input style="width: 250px;border:0;border-bottom:1px solid #ccc;outline: none;background-color: #fff;" type="password" name="passwd" oninput="cacheInput(this);" placeholder="密码" required>
          <input type="submit" value="登录" style="background-color: rgba(3,119,165,100); width:250px; color: white;">
        </form>
      </div>
    </div>
  </div>
  <script>

    if (localStorage.getItem('token')) {
      try {
        let u = localStorage.getItem('userinfo')
        if (u) {
          let uinfo = JSON.parse(u)
          if (uinfo.expires + uinfo.time > Date.now()) {
            location.href = '/home'
          }
        }
      } catch(err) {
        console.error(err)
      }
    }

    let loginfo = {
      username : '',
      passwd : ''
    }

    function cacheInput (t) {
      if (t.name === 'username') {
        loginfo.username = t.value.trim()
      } else if (t.name === 'passwd') {
        loginfo.passwd = t.value
      }
    }

    function login(t) {
      if (loginfo.username === '' || loginfo.passwd === '') {
        return
      }

      fetch('/login', {
        method : 'POST',
        headers : {
          'content-type' : 'text/plain'
        },
        body : JSON.stringify(loginfo)
      }).then(async res => {
        if (!res.ok) {
          let errtext = await res.text()
          throw new Error(`${res.status} : ${errtext}`)
        } else {
          return res.json()
        }
      }).then(d => {
        localStorage.setItem('token', d.token)
        localStorage.setItem('userinfo', JSON.stringify(d.userinfo))
        location.href = '/home'
      }).catch(err => {
        alert(err)
      })
    }
  </script>
</body>
</html>
